package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.PageVo;
import com.itheima.admin.dto.DeptDto;
import com.itheima.admin.dto.PageDto;
import com.itheima.admin.mapper.DeptMapper;
import com.itheima.admin.pojo.Dept;
import com.itheima.admin.pojo.Role;
import com.itheima.admin.service.IDeptService;
import com.itheima.admin.vo.DeptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public PageVo<DeptVo> queryByPage(PageDto pageDto) {
        IPage<Dept> page = new Page<>(pageDto.getCurrentPage(),
                pageDto.getPageSize());
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("dept_name",pageDto.getQueryString());
        IPage<Dept> deptIPage = deptMapper.selectPage(page, queryWrapper);
        List<DeptVo> collect = deptIPage.getRecords().stream().map(
                dept -> {
                    DeptVo deptVo = new DeptVo();
                    BeanUtils.copyProperties(dept,deptVo);
                    return deptVo;
                }
        ).collect(Collectors.toList());
        return new PageVo<DeptVo>(collect,(int)deptIPage.getTotal());
    }

    @Override
    public List<DeptVo> queryAll() {
        List<Dept> deptVoList = deptMapper.selectList(null);
        List<DeptVo> collect =
                deptVoList.stream().map(dept -> {
                    DeptVo deptVo = new DeptVo();
                    BeanUtils.copyProperties(dept,deptVo);
                    return deptVo;
                }).collect(Collectors.toList());
        return collect ;
    }

    @Override
    public boolean insertDept(DeptDto deptDto) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptDto,dept);
        String id = UUID.randomUUID().toString();
        dept.setDeptId(id);
        return deptMapper.insert(dept) > 0;
    }

    @Override
    public boolean deleteDept(String id) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("dept_id",id);
        return deptMapper.delete(queryWrapper)>0;
    }

    @Override
    public DeptDto queryById(String id) {
        Dept dept = deptMapper.selectById(id);
        DeptDto DeptDto = new DeptDto();
        BeanUtils.copyProperties(dept,DeptDto);
        return DeptDto;
    }

    @Override
    public boolean editDept(Dept dept) {
        return deptMapper.updateById(dept)>0;
    }
}
